package com.zspringboot.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zspringboot.demo.common.Result;
import com.zspringboot.demo.config.baiduapi.TransApi;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/translate")
public class BaiduTranslateApiController {
    // 传入id和密钥
    private static final String APP_ID = "20230228001579571";
    private static final String SECURITY_KEY = "uDStlq0N5CeCQmkLkPp0";


    /**
     * 翻译接口，调用的百度api
     * @param textarea 传入的参数值
     * @return 返回JSON 数据
     */

    @PostMapping("/")
    @Operation(summary = "翻译接口", description = "翻译")
//    @Parameter(name = "textarea", description = "传入的翻译内容")
//    @ApiParam(name = "textarea",value = "传入翻译内容",required = true)
    public Result tran(@ApiParam("翻译内容") @RequestParam(defaultValue = "") String textarea){
        if (textarea.equals(""))
            return Result.error();
        TransApi api = new TransApi(APP_ID,SECURITY_KEY);
        // 设置传入语言
        String SetIncomingLanguage = "auto";
        // 设置翻译语言
        String SetTranslationLanguage = "en";
        JSONObject job =
                JSON.parseObject(api.getTransResult(textarea,SetIncomingLanguage,SetTranslationLanguage));
        // 判断传入的语言是否为中文
        if (!job.get("from").equals("zh"))
            // 如果不是中文，将翻译语言设置为中文
            SetTranslationLanguage = "zh";

        return Result.success(api.getTransResult(textarea,SetIncomingLanguage,SetTranslationLanguage));
    }

//    public static void main(String[] args) {
//        TransApi api = new TransApi(APP_ID,SECURITY_KEY);
//        // 设置传入语言
//        String SetIncomingLanguage = "auto";
//        // 设置翻译语言
//        String SetTranslationLanguage = "en";
////        JSONObject jsonObject = JSONObject.
//        JSONObject job =
//                JSON.parseObject(api.getTransResult("喜洋洋",SetIncomingLanguage,SetTranslationLanguage));
//
//        System.out.println(job);
//        System.out.println(job.get("from"));
//        System.out.println(job.get("to"));
//
//        JSONArray a = JSON.parseArray(job.get("trans_result").toString());
//        JSONObject b =
//                JSON.parseObject(a.getString(0));
//        System.out.println(b.get("dst"));
//        System.out.println(b.get("src"));
//
//
//        //        System.out.println((api.getTransResult("喜洋洋",SetIncomingLanguage,SetTranslationLanguage)));
//    }


}
